//
//  EditShareTimeViewController.m
//  QRMaster
//
//  Created by myApple on 15/7/27.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "EditShareTimeViewController.h"
#import "shareDimensionalView.h"
#import "TouchBtnColor.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "Reachability.h"
#import "StartPageController.h"
#import "validateInputValue.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "AreaChooseController.h"
#import "IQKeyboardManager.h"

#import "shareDimensionalView.h"
#import <ShareSDK/ShareSDK.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ShareUIView.h"
#import <MessageUI/MessageUI.h>
@interface EditShareTimeViewController ()<shareDimensionaViewDelegate,UITextFieldDelegate,ABPeoplePickerNavigationControllerDelegate,UINavigationControllerDelegate,MFMessageComposeViewControllerDelegate,ShareViewDelegate>
{
    NSString * beginTime;
    NSString * endTime;
    UIButton * sharebtn;
    UITextField * mobileTextField;
    
    UIButton * mobileBtn;
    UIButton * emailBtn;
    UIButton * mobileHeaderBtn;
    UIButton * addAddressTelePhoneBtn;
    UILabel * emailHeaderLabel;
    UILabel * areaCodeIdLabel;
    UILabel * areaLabel;
    
    id<ISSContent> publishContent; //分享内容
    NSData * imgData;
    NSData * shareLinkImgData;
    ShareUIView * shareView;  //分享view
    NSString * linkURLNO;
    shareDimensionalView * sdv;
    
    //多语言
    UILabel * titleLabel;
}

@end

@implementation EditShareTimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    beginTime = nil;
    endTime = nil;
    // Do any additional setup after loading the view.
    [self prepareTitleView];
    [self prepareTelephoneView];
    [self prepareView];
    [self prepareShareView];
    
    shareLinkImgData = UIImageJPEGRepresentation([UIImage imageNamed:@"ic_锁掌柜_70"],1.0);
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"selectIndexCause" object:nil];
    self.title = NSLocalizedString(@"setShareTime", nil);
    sharebtn.hidden = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    sharebtn.hidden = YES;
    [[IQKeyboardManager sharedManager]setEnable:YES];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

-(void)prepareTitleView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = ScreenWidth - 50;
    float y = 2;
    float width = 40;
    float height = 40;
    
    sharebtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [sharebtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
    [sharebtn setBackgroundImage:[TouchBtnColor imageWithColor:[UIColor grayColor] size:sharebtn.frame.size] forState:UIControlStateHighlighted];
    [self.navigationController.navigationBar addSubview:sharebtn];
    
    x = 10;
    y = 10;
    width = 20;
    height = 20;
    UIImageView * sureImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    sureImgView.image = [UIImage imageNamed:@"ic_save"];
    [sharebtn addSubview:sureImgView];
    
}

//选择时间页面
-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 50;
    float width = ScreenWidth;
    float height = ScreenHeight - y;
    shareDimensionalView * sdv = [[shareDimensionalView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    sdv.delegate = self;
    [self.view addSubview:sdv];
}

//填写电话号码
-(void)prepareTelephoneView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 80;
    float y = 10;
    float width = ScreenWidth - x - 10;
    float height = 40;
    
    //手机号码
    mobileTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    mobileTextField.borderStyle = UITextBorderStyleRoundedRect;
    mobileTextField.keyboardType = UIKeyboardTypeNumberPad;
    mobileTextField.placeholder = NSLocalizedString(@"shareMobile", nil);
    mobileTextField.delegate = self;
    [self.view addSubview:mobileTextField];
    
    //前面点击的区号按钮
    x = 20;
    y = 10;
    width = 70;
    mobileHeaderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    mobileHeaderBtn.frame = CGRectMake(x, y, width, height);
    [mobileHeaderBtn addTarget:self action:@selector(chooseArea) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:mobileHeaderBtn];
    
    areaCodeIdLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 60, 15)];
    areaCodeIdLabel.text = [NSString stringWithFormat:@"+%@",[QRSingleton sharedQRSingleton].currentAreaCodeString];
    areaCodeIdLabel.font = [UIFont systemFontOfSize:10.0];
    [mobileHeaderBtn addSubview:areaCodeIdLabel];
    
    areaLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 15, 60, 15)];
    areaLabel.font = [UIFont systemFontOfSize:10.0];
    areaLabel.text = [QRSingleton sharedQRSingleton].currentAreaString;
    [mobileHeaderBtn addSubview:areaLabel];
    
    emailHeaderLabel = [[UILabel alloc]initWithFrame:CGRectMake(mobileHeaderBtn.frame.origin.x, mobileHeaderBtn.frame.origin.y + 10, mobileHeaderBtn.frame.size.width, mobileHeaderBtn.frame.size.height)];
    emailHeaderLabel.text = NSLocalizedString(@"mineEmail", nil);
    emailHeaderLabel.hidden = YES;
    emailHeaderLabel.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:emailHeaderLabel];
    
    x = mobileTextField.frame.size.width - 40;
    y = 0;
    width = 40;
    height = 40;
    addAddressTelePhoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addAddressTelePhoneBtn.frame = CGRectMake(x, y, width, height);
    [addAddressTelePhoneBtn setBackgroundColor:RGBA(135, 199, 66, 1)];
    [addAddressTelePhoneBtn setBackgroundImage:nil forState:0];
    [addAddressTelePhoneBtn addTarget:self action:@selector(addTelePhone) forControlEvents:UIControlEventTouchUpInside];
    mobileTextField.rightView = addAddressTelePhoneBtn;
    mobileTextField.rightViewMode = UITextFieldViewModeAlways;
    UIImageView * adderssImgView = [[UIImageView alloc]initWithFrame:CGRectMake(5,5, 30, 30)];
    adderssImgView.image = [UIImage imageNamed:@"ic_txl"];
    [addAddressTelePhoneBtn addSubview:adderssImgView];
}

-(void)prepareShareView
{
    shareView = [[ShareUIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    shareView.delegate = self;
    shareView.hidden = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:shareView];
    
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - y;
    sdv = [[shareDimensionalView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    sdv.hidden = YES;
    [self.view addSubview:sdv];
}

#pragma mark ---------- 改变地区或者国家
-(void)chooseArea
{
    AreaChooseController * acc = [[AreaChooseController alloc]init];
    [self.navigationController pushViewController:acc animated:YES];
    acc.areaCode = ^(NSString * areaCodeString,NSString * areaString)
    {
        areaCodeIdLabel.text = [NSString stringWithFormat:@"+%@",areaCodeString];
        areaLabel.text = areaString;
    };
}


#pragma mark -- 从通讯录添加职员
-(void)addTelePhone
{
    ABPeoplePickerNavigationController * peoplePicker = [[ABPeoplePickerNavigationController alloc]init];
    peoplePicker.peoplePickerDelegate = self;
    [self presentViewController:peoplePicker animated:NO completion:nil];
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
{
    ABMutableMultiValueRef phoneMult = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString * fisrtName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString * lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (fisrtName == nil) {
        fisrtName = @"";
    }
    if (lastName == nil) {
        lastName = @"";
    }
    mobileTextField.text = [NSString stringWithFormat:@"%@%@",lastName,fisrtName];
    
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMult); i ++) {
        NSString * aphone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMult, i);
        [phones addObject:aphone];
    }
    if (phones.count > 0) {
        mobileTextField.text = [phones objectAtIndex:0];
        mobileTextField.text = [mobileTextField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

//2_0到8_0系统使用的方法
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    ABMutableMultiValueRef phoneMult = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString * fisrtName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString * lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (fisrtName == nil) {
        fisrtName = @"";
    }
    if (lastName == nil) {
        lastName = @"";
    }
    mobileTextField.text = [NSString stringWithFormat:@"%@%@",lastName,fisrtName];
    
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMult); i ++) {
        NSString * aphone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMult, i);
        [phones addObject:aphone];
    }
    if (phones.count > 0) {
        mobileTextField.text = [phones objectAtIndex:0];
        mobileTextField.text = [mobileTextField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    return NO;
}

-(void)sureClick
{
    [mobileTextField resignFirstResponder];
    if (endTime == nil || [endTime isEqualToString:@""]) {
        [PromptInfoView showMessage:NSLocalizedString(@"endTimeNil", nil) superView:self.view];
        return;
    }
    if (beginTime == nil || [beginTime isEqualToString:@""]) {
        [PromptInfoView showMessage:NSLocalizedString(@"beginTimeNil", nil) superView:self.view];
        return;
    }
    if (![validateInputValue isPureNumandCharacters:mobileTextField.text]) {
        [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil) superView:self.view];
        return;
    }
    if (mobileTextField.text == nil || [mobileTextField.text isEqualToString:@""]) {
        [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil) superView:self.view];
        return;
    }
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:_roomId forKey:@"roomId"];
    [postDict setValue:endTime forKey:@"endTime"];
    [postDict setValue:beginTime forKey:@"startTime"];
    [postDict setValue:mobileTextField.text forKey:@"mobile"];
    [postDict setValue:[areaCodeIdLabel.text substringFromIndex:1]forKey:@"areaCode"];
    __weak EditShareTimeViewController * weakSelf = self;
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [rnk initWithPath:POST(ADDCLIENTSHARE) params:postDict block:^(id downLoadData, id error) {
        if (downLoadData != nil)
        {
            id data = [downLoadData objectForKey:@"data"];
            DDLOG(@"分享数据=%@",downLoadData);
            DDLOG(@"_surePost = %@",_surePost);
//            if (_surePost)
//            {
//                _surePost(data,[NSString stringWithFormat:@"%@%@",[areaCodeIdLabel.text substringFromIndex:1],mobileTextField.text]);
//            }
//            [weakSelf.navigationController popViewControllerAnimated:YES];
            linkURLNO = data;
            if (data) {
                [self shareType];
                
            }
        }
        else if (error != nil)
        {
            DDLOG(@"分享error = %@",error);
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
            
        }
        [weakSelf stopWaiting];
    }];
}

-(void)shareType
{
    //构造分享内容
    publishContent = [ShareSDK content:NSLocalizedString(@"shareContent", nil)
                         defaultContent:NSLocalizedString(@"shareDefualt", nil)
                                  image:[ShareSDK imageWithData:imgData fileName:@"image" mimeType:@"jpg"]
                                  title:NSLocalizedString(@"shareTitle", nil)
                                    url:nil
                            description:nil
                              mediaType:SSPublishContentMediaTypeImage];
    [publishContent addQQUnitWithType:[NSNumber numberWithInt:SSPublishContentMediaTypeNews] content:NSLocalizedString(@"shareContent", nil) title:NSLocalizedString(@"shareTitle", nil) url:[NSString stringWithFormat:@"%@",linkURLNO] image:[ShareSDK imageWithData:shareLinkImgData fileName:@"image" mimeType:@"jpg"]];
    [publishContent addWeixinSessionUnitWithType:[NSNumber numberWithInt:SSPublishContentMediaTypeNews] content:NSLocalizedString(@"shareContent", nil) title:NSLocalizedString(@"shareTitle", nil) url:[NSString stringWithFormat:@"%@",linkURLNO] image:[ShareSDK imageWithData:shareLinkImgData fileName:@"image" mimeType:@"jpg"] musicFileUrl:nil extInfo:nil fileData:nil emoticonData:nil];
    
    shareView.hidden = NO;
    
}

#pragma mark ----- 分享点击图片事件
-(void)shareClick:(NSInteger)shareIndex
{
    [self cancelShare];
    int shareType = 0;
    if (shareIndex == 2) {
        [self sendSMS];
        return;
    }
    else if (shareIndex == 0) {
        shareType = ShareTypeQQ;
    }
    else if (shareIndex == 1)
    {
        shareType = ShareTypeWeixiSession;
    }
    
    [ShareSDK showShareViewWithType:shareType container:nil content:publishContent statusBarTips:YES authOptions:nil shareOptions:nil result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        DDLOG(@"分享是否成功=%d",state);
        if (state == SSResponseStateFail)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"shareFail", nil)] ;
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
}

#pragma mark ------取消分享
-(void)cancelShare
{
    shareView.hidden = YES;
}

#pragma mark --------  发送短信
-(void)sendSMS
{
    if ([MFMessageComposeViewController canSendText]) {
        MFMessageComposeViewController * messageController = [[MFMessageComposeViewController alloc]init];
        messageController.delegate = self;
        messageController.messageComposeDelegate = self;
        NSString * messageContent = [NSString stringWithFormat:@"%@%@%@",NSLocalizedString(@"messageFirst", nil), linkURLNO,NSLocalizedString(@"messageSecond", nil)];
        messageController.body = messageContent;
        messageController.recipients = @[mobileTextField.text];
        [self presentViewController:messageController animated:YES completion:^{
            [self cancelShare];
        }];
    }
    else
    {
        [PromptInfoView showMessage:NSLocalizedString(@"shareFail", nil)] ;
    }
    
}

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark == delegate
-(void)shareDimensionaViewSendTime:(NSString *)time typeTime:(BOOL)type
{
    if (type) {
        endTime = time;
    }else
    {
        beginTime = time;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
